package com.qian.fmall.order.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.wxpay.sdk.WXPay;
import com.qian.fmall.commons.ResultSet;
import com.qian.fmall.mapper.CartMapper;
import com.qian.fmall.mapper.OrderMapper;
import com.qian.fmall.mapper.ProductSkuMapper;
import com.qian.fmall.order.config.AlipayProperty;
import com.qian.fmall.order.config.WxPayConfig;
import com.qian.fmall.order.orderInterface.OrderService;
import com.qian.fmall.pojo.Orders;
import com.qian.fmall.pojo.ProductSku;
import com.qian.fmall.pojo.ShoppingCart;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@DubboService
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private CartMapper cartMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private AlipayProperty ap;
    @Resource
    private WxPayConfig wx;

    @Override
    @Transactional
    public ResultSet addOrder(int[] arr, Orders orders) {
        int order = orderMapper.createOrder(orders);
        int payType = orders.getPayType();
        HashMap<String, Object> payMap = new HashMap<>();
        payMap.put("orderId", orders.getOrderId());
        payMap.put("info", orders.getTotalAmount());
        payMap.put("orderName", orders.getUntitled());
        if (payType == 1) {
            System.out.println("0------------进入微信pay");
            HashMap<String, String> data = new HashMap<>();
            WXPay wxPay = new WXPay(wx);
            data.put("body", orders.getUntitled());
            data.put("out_trade_no", orders.getOrderId());
            data.put("fee_type", "CNY");
            data.put("total_fee", "1");
            //data.put("total_fee",orders.getTotalAmount());
            data.put("trade_type", "NATIVE");
            data.put("notify_url", "http://mikeqian.free.idcfengye.com/wPay/success");
            try {
                Map<String, String> map = wxPay.unifiedOrder(data);
                String code_url = map.get("code_url");
                payMap.put("payUrl", code_url);
                payMap.put("payType", 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(ap.getGatewayUrl(), ap.getAppId(), ap.getMerchantPrivateKey(), "json", ap.getCharset(), ap.getAlipayPublicKey(), ap.getSignType());
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(ap.getReturnUrl());
            alipayRequest.setNotifyUrl(ap.getNotifyUrl());
            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = orders.getOrderId();
            //付款金额，必填
            String total_amount = orders.getTotalAmount();
            //订单名称，必填
            String subject = orders.getUntitled();
            //商品描述，可空
            String body = orders.getOrderRemark();

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            try {
                String result = alipayClient.pageExecute(alipayRequest).getBody();
                payMap.put("payUrl", result);
                payMap.put("payType", 2);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
        if (order > 0) {
            //修改SKU
            int modifyRow = 0;
            for (int cartId : arr) {
                //获取购物车数据
                ShoppingCart cart = cartMapper.getShoppingCartByCartId(cartId);
                //得到productSku数据
                ProductSku productSku = productSkuMapper.getProductSkuBySkuId(cart.getSkuId());
                //修改sku中库存
                int skuNum = Integer.parseInt(cart.getCartNum());
                if (productSku.getStock() > skuNum) {
                    modifyRow += productSkuMapper.modifyStockBySkuId(cart.getSkuId(), productSku.getStock() - skuNum);
                }
                if (modifyRow != arr.length) {
                    return ResultSet.error("提交订单失败");
                }
                //删除购物车信息
                int delRows = cartMapper.batchDelCartByCards(cartId);
            }
            return ResultSet.ok("success", payMap);
        }
        return ResultSet.ok("提交订单失败");
    }

    @Override
    public int updateOrderStatus(String orderId, String s) {
        return orderMapper.updateOrderStatusByStatus(orderId, s);
    }
}
